package com.xujiang.myblog.model;

import android.content.Context;

import com.xujiang.myblog.tools.Common;
import com.xujiang.myblog.util.Callback3;
import com.xujiang.myblog.util.L;
import com.xujiang.myblog.util.PreferencesUtils;

import org.joda.time.DateTime;

import java.util.Date;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by xujiang on 2017/4/21.
 */

public class PreferUser {
    /**
     * 这是一个本地存储模型
     * SharedPreferences的存储
     *
     * */
    private static final String TAG = PreferUser.class.getSimpleName();

    /**
     * SharedPreferences为xml文件方式的存储
     * 下面定义的是一些文件的名称
     * */
    private final static String PREFERENCE_USER_FILE_NAME  = "user_info";
    public final static String PREFERENCE_LOGIN_HISTORY_FILE_NAME = "user_history";
    private final static String PREFERENCE_LOGIN_FILE_NAME                 = "user_login";

    /**
     * 为避免保存时键的不一至导致的读取错误
     * 将要保存的键统一定义出来，如果以后要添加
     * 请先定义
     * */
    private final static String PREFERENCE_USER_ID         = "user_id";
    private final static String PREFERENCE_NICK_NAME       = "nick_name";
    private final static String PREFERENCE_LOGIN_PASSWORD                  = "user_password";
    private final static String PREFERENCE_USER_HEADPICTURE_URL = "user_avatar_url";
    private final static String PREFERENCE_LOGIN_USER_TOKEN              = "user_token";
    private final static String PREFERENCE_ID         = "id";

    /**
     * 全局登陆变量
     * 由于在MApplication中持有一个本类的变量
     * 保证了他的全局性
     * */
    private boolean login;//当前是否登录
    /**
     * 保存的值的变量
     *
     * */
    private String  userId;//用户id
    private String  nickName;//用户名
    private String  id;//用户唯一标识
    private String  password;//用户密码 ,md5
    private String  headPicture;//用户头像
    private String  token;

    public boolean isLogin() {
        return login;
    }


    public PreferUser setvalue(UserInfo userinfo){
        this.login = true;
        this.userId = userinfo.getUserId();
        this.nickName = userinfo.getNickName();
        this.id = userinfo.getId();
        this.token = userinfo.getToken();
        this.headPicture = userinfo.getHeadPicture();
        return this;

    }

    public PreferUser setLogin(boolean login) {
        this.login = login;
        return this;
    }

    public String getUserId() {
        return userId;
    }

    public PreferUser setUserId(String userId) {
        this.userId = userId;
        return this;
    }

    public String getNickName() {
        return nickName;
    }

    public PreferUser setNickName(String nickName) {
        this.nickName = nickName;
        return this;
    }

    public String getId() {
        return id;
    }

    public PreferUser setId(String id) {
        this.id = id;
        return this;
    }

    public String getPassword() {
        return password;
    }

    public PreferUser setPassword(String password) {
        this.password = password;
        return this;
    }

    public String getHeadPicture() {
        return headPicture;
    }

    public PreferUser setHeadPicture(String headPicture) {
        this.headPicture = headPicture;
        return this;
    }

    public String getToken() {
        return token;
    }

    public PreferUser setToken(String token) {
        this.token = token;
        return this;
    }

    @Override
    public String toString() {
        return "PreferUser{" +
                "login=" + login +
                ", userId='" + userId + '\'' +
                ", nickName='" + nickName + '\'' +
                ", id='" + id + '\'' +
                ", password='" + password + '\'' +
                ", headPicture='" + headPicture + '\'' +
                ", token='" + token + '\'' +
                '}';
    }


    private static PreferUser preferUser;
    /**
     * 某时刻全局线程只有一个实体
     *
     * */
    public static synchronized PreferUser get() {
        if (preferUser == null) {
            synchronized (PreferUser.class) {
                if (preferUser == null) {
                    preferUser = new PreferUser();
                }
            }
        }
        return preferUser;
    }
    /**
     * 保存数据apply和commit是一个意思，具体区别请百度
     *
     * */
    public void saveUserInfo(){
        PreferencesUtils.from(PreferUser.PREFERENCE_USER_FILE_NAME)
                .put(PreferUser.PREFERENCE_USER_ID,userId)
                .put(PreferUser.PREFERENCE_NICK_NAME,nickName)
                .put(PreferUser.PREFERENCE_ID,id)
                .put(PreferUser.PREFERENCE_LOGIN_PASSWORD,password)
                .put(PreferUser.PREFERENCE_USER_HEADPICTURE_URL,headPicture)
                .put(PreferUser.PREFERENCE_LOGIN_USER_TOKEN,token)
                .apply();
        L.d(TAG, "saveUserInfo : %s", this);
    }

    public PreferUser(){

    }

    public void logout(){
        clear();
    }
    /**
     * 清除变量和user_info文件中的数据
     *
     * */
    public void clear() {
        L.d(TAG, "clear : %s ", this);
        setHeadPicture(null).setUserId(null).setNickName(null).setId(null).setPassword(null)
                .setLogin(false)
                .setToken(null);
        //PreferencesUtils.from(PREFERENCE_LOGIN_FILE_NAME).clear();
        PreferencesUtils.from(PREFERENCE_USER_FILE_NAME).clear();
    }


    /**
     * 读取登录用户信息
     */
    public void readLoginInfo() {
        PreferencesUtils userInfo = PreferencesUtils.from(PREFERENCE_USER_FILE_NAME);
        this.userId = userInfo.getString(PreferUser.PREFERENCE_USER_ID);
        this.nickName = userInfo.getString(PreferUser.PREFERENCE_NICK_NAME);
        this.headPicture = userInfo.getString(PreferUser.PREFERENCE_USER_HEADPICTURE_URL);

        this.id = userInfo.getString(PreferUser.PREFERENCE_ID);
        this.password = userInfo.getString(PreferUser.PREFERENCE_LOGIN_PASSWORD);
        this.token = userInfo.getString(PREFERENCE_LOGIN_USER_TOKEN);
        L.d(TAG, "readLoginInfo : %s", this);
    }


    /**
     * IO线程保存登录与用户信息
     * @param callback
     *
     * http://blog.csdn.net/lisdye2/article/details/51113837
     *
     * subscribeOn()改变的是订阅的线程，即call()执行的线程。
    observeOn()改变的是发送的线程，即onNext()的过程，注意，即我们在逻辑中通过操作符对数据进行修改都是在发送的过程中。除了最初Observable创建的过程。
     */
    public void saveInfo(final Callback3 callback) {
        Observable.just("")
                .subscribeOn(Schedulers.io())
                .map(new Func1<String, Object>() {
                    @Override public Object call(String s) {
                        saveLoginInfo();
                        saveUserInfo();
                        return null;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Object>() {
                    @Override public void call(Object o) {
                        L.d(TAG, "saveInfo : %s", PreferUser.this);
                        callback.onSuccess();
                    }
                }, new Action1<Throwable>() {
                    @Override public void call(Throwable throwable) {
                        L.Log.w(TAG,throwable);
                        callback.onError(throwable);
                    }
                });
    }

    /**
     * 保存历史记录
     * */
    public void saveLoginInfo() {
        PreferencesUtils.from(PreferUser.PREFERENCE_LOGIN_HISTORY_FILE_NAME, Context.MODE_APPEND)
                .put(PreferUser.PREFERENCE_USER_ID, userId).apply();

//        PreferencesUtils.from(PreferUser.PREFERENCE_LOGIN_FILE_NAME)
//                .put(PreferUser.PREFERENCE_USER_ID, userId)
//                .put(PreferUser.PREFERENCE_ID, id)
//                .put(PreferUser.PREFERENCE_LOGIN_PASSWORD, password)
//                .put(PreferUser.PREFERENCE_LOGIN_USER_TOKEN, token)
//                .apply();
        L.d(TAG, "saveLoginInfo : %s", this);
    }



}
